<template>
  <div>
    <!-- 拖拽上传之限制文件大小，限制类型 -->
    <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" multiple
      :limit="uploadFile.limit" :before-upload="beforeUpload" :on-exceed="onExceed" :drag="uploadFile.drag"
      :on-error="handleUploadError" :on-success="handleUploadSuccess" :disabled="loading">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">文件大小不得超过5M</div>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false, // 按钮loading与禁用上传
      text: '点击上传',
      uploadFile: {
        action: 'https://jsonplaceholder.typicode.com/posts/', // 上传地址
        multiple: true, // 多选
        limit: 3, // 限制几个
        headers: {
          Authorization: "Bearer " + 'token', // 接口的token
        },
        drag: true,
        fileType: ["doc", "xls", "ppt", "txt", "pdf", "png"],
        fileSize: 0.5
      }
    }
  },
  methods: {
    // 上传前
    beforeUpload(file) {
      this.loading = true
      this.text = '上传中'
      // 校检文件大小
      const isLt = file.size / 1024 / 1024 < this.uploadFile.fileSize;
      if (!isLt) {
        this.$message({
          message: `上传文件大小不能超过 ${this.uploadFile.fileSize} MB!`,
          type: 'warning'
        });
        this.loading = false
        this.text = '点击上传'
        return false;
      }
      // 校验文件类型
      if (this.uploadFile.fileType.length) {
        const fileNameType = file.type
        const length = fileNameType.lastIndexOf('/')
        const fileName = fileNameType.substring(length + 1)
        if (!this.uploadFile.fileType.includes(fileName)) {
          this.loading = false
          this.text = '点击上传'
          this.$message({
          message: `请上传${this.uploadFile.fileType.join(',')}格式的文件`,
          type: 'warning'
        });
          return false
        }
      }
    },
    // 文件上传个数超出限制时的钩子
    onExceed(files, fileList) {
      this.$message({
        message: `一次最大上传个数为3个，您本次上传${files.length}个`,
        type: 'warning'
      });
    },
    // 文件上传失败的钩子
    handleUploadError(err, file, fileList) {
      this.loading = false
      this.text = '点击上传'
      this.$message({
        message: `上传失败，请联系管理员`,
        type: 'error'
      });
    },
    // 文件上传成功的钩子
    handleUploadSuccess(response, file, fileLis) {
      this.loading = false
      this.text = '点击上传'
      this.$message({
        message: `上传成功`,
        type: 'error'
      });
    },
  }
}
</script>

<style lang="scss" scoped>
</style>